package com.jlwl.houseservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlwl.houseservice.entity.ServiceCategory;
import com.jlwl.houseservice.entity.SpecialService;
import com.jlwl.houseservice.entity.SpecialServiceImage;
import com.jlwl.houseservice.mapper.SpecialServiceImageMapper;
import com.jlwl.houseservice.mapper.SpecialServiceMapper;
import com.jlwl.houseservice.service.ServiceCategoryService;
import com.jlwl.houseservice.service.SpecialServiceService;
import com.jlwl.houseservice.vo.SpecialServiceDetailVO;
import com.jlwl.houseservice.vo.SpecialServiceQueryVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 特色服务Service实现类
 */
@Service
public class SpecialServiceServiceImpl extends ServiceImpl<SpecialServiceMapper, SpecialService> implements SpecialServiceService {

    @Autowired
    private ServiceCategoryService serviceCategoryService;

    @Autowired
    private SpecialServiceImageMapper specialServiceImageMapper;

    @Override
    public Page<SpecialService> pageList(SpecialServiceQueryVO queryVO) {
        LambdaQueryWrapper<SpecialService> queryWrapper = new LambdaQueryWrapper<>();
        
        // 关键词搜索
        if (StringUtils.hasText(queryVO.getKeyword())) {
            queryWrapper.and(wrapper -> wrapper
                    .like(SpecialService::getName, queryVO.getKeyword())
                    .or()
                    .like(SpecialService::getDescription, queryVO.getKeyword())
            );
        }
        
        // 分类筛选
        if (queryVO.getCategoryId() != null) {
            queryWrapper.eq(SpecialService::getCategoryId, queryVO.getCategoryId());
        }
        
        // 价格范围筛选
        if (queryVO.getMinPrice() != null) {
            queryWrapper.ge(SpecialService::getPrice, queryVO.getMinPrice());
        }
        
        if (queryVO.getMaxPrice() != null) {
            queryWrapper.le(SpecialService::getPrice, queryVO.getMaxPrice());
        }
        
        // 状态筛选
        if (queryVO.getStatus() != null) {
            queryWrapper.eq(SpecialService::getStatus, queryVO.getStatus());
        } else {
            // 默认只查询上架的服务
            queryWrapper.eq(SpecialService::getStatus, 1);
        }
        
        // 推荐筛选
        if (queryVO.getIsRecommended() != null) {
            queryWrapper.eq(SpecialService::getIsRecommended, queryVO.getIsRecommended());
        }
        
        // 默认按创建时间倒序排序
        queryWrapper.orderByDesc(SpecialService::getCreatedAt);
        
        // 分页查询
        return page(new Page<>(queryVO.getPage(), queryVO.getSize()), queryWrapper);
    }

    @Override
    public SpecialServiceDetailVO getServiceDetail(Integer id) {
        // 获取特色服务信息
        SpecialService specialService = getById(id);
        if (specialService == null) {
            return null;
        }
        
        // 获取分类信息
        ServiceCategory category = serviceCategoryService.getById(specialService.getCategoryId());
        
        // 获取图片列表
        List<String> images = getServiceImages(id);
        
        // 获取相关推荐服务
        List<SpecialService> recommendServices = getRecommendServicesByCategoryId(specialService.getCategoryId(), id, 4);
        
        // 构建返回结果
        SpecialServiceDetailVO detailVO = new SpecialServiceDetailVO();
        detailVO.setSpecialService(specialService);
        detailVO.setCategory(category);
        detailVO.setImages(images);
        detailVO.setRecommendServices(recommendServices);
        
        return detailVO;
    }

    @Override
    public List<SpecialService> getRecommendServices(Integer limit) {
        return list(new LambdaQueryWrapper<SpecialService>()
                .eq(SpecialService::getStatus, 1)
                .eq(SpecialService::getIsRecommended, 1)
                .orderByDesc(SpecialService::getSalesCount)
                .last("LIMIT " + limit));
    }

    @Override
    public List<SpecialService> getServicesByCategory(Integer categoryId, Integer limit) {
        return list(new LambdaQueryWrapper<SpecialService>()
                .eq(SpecialService::getCategoryId, categoryId)
                .eq(SpecialService::getStatus, 1)
                .orderByDesc(SpecialService::getCreatedAt)
                .last("LIMIT " + limit));
    }

    @Override
    @Transactional
    public boolean createService(SpecialService specialService, List<String> imageUrls) {
        // 设置初始值
        specialService.setSalesCount(0);
        specialService.setRating(new BigDecimal("5.0"));
        specialService.setReviewCount(0);
        specialService.setCreatedAt(LocalDateTime.now());
        specialService.setUpdatedAt(LocalDateTime.now());
        
        // 保存特色服务
        boolean success = save(specialService);
        if (!success) {
            return false;
        }
        
        // 保存图片
        if (imageUrls != null && !imageUrls.isEmpty()) {
            saveServiceImages(specialService.getId(), imageUrls);
        }
        
        return true;
    }

    @Override
    @Transactional
    public boolean updateService(SpecialService specialService, List<String> imageUrls) {
        SpecialService existService = getById(specialService.getId());
        if (existService == null) {
            return false;
        }
        
        specialService.setUpdatedAt(LocalDateTime.now());
        
        // 更新特色服务
        boolean success = updateById(specialService);
        if (!success) {
            return false;
        }
        
        // 更新图片
        if (imageUrls != null) {
            // 删除旧图片
            deleteServiceImages(specialService.getId());
            
            // 保存新图片
            if (!imageUrls.isEmpty()) {
                saveServiceImages(specialService.getId(), imageUrls);
            }
        }
        
        return true;
    }

    @Override
    @Transactional
    public boolean deleteService(Integer id) {
        // 删除图片
        deleteServiceImages(id);
        
        // 删除特色服务
        return removeById(id);
    }

    @Override
    @Transactional
    public boolean updateServiceStatus(Integer id, Integer status) {
        return update(new LambdaUpdateWrapper<SpecialService>()
                .eq(SpecialService::getId, id)
                .set(SpecialService::getStatus, status)
                .set(SpecialService::getUpdatedAt, LocalDateTime.now()));
    }

    @Override
    @Transactional
    public boolean updateServiceRecommendStatus(Integer id, Integer isRecommended) {
        return update(new LambdaUpdateWrapper<SpecialService>()
                .eq(SpecialService::getId, id)
                .set(SpecialService::getIsRecommended, isRecommended)
                .set(SpecialService::getUpdatedAt, LocalDateTime.now()));
    }
    
    /**
     * 获取服务图片列表
     */
    private List<String> getServiceImages(Integer serviceId) {
        List<SpecialServiceImage> images = specialServiceImageMapper.selectList(
                new LambdaQueryWrapper<SpecialServiceImage>()
                        .eq(SpecialServiceImage::getServiceId, serviceId)
                        .orderByAsc(SpecialServiceImage::getDisplayOrder)
        );
        
        return images.stream()
                .map(SpecialServiceImage::getImageUrl)
                .collect(Collectors.toList());
    }
    
    /**
     * 保存服务图片
     */
    private void saveServiceImages(Integer serviceId, List<String> imageUrls) {
        int order = 0;
        for (String imageUrl : imageUrls) {
            SpecialServiceImage image = new SpecialServiceImage();
            image.setServiceId(serviceId);
            image.setImageUrl(imageUrl);
            image.setDisplayOrder(order++);
            image.setCreatedAt(LocalDateTime.now());
            image.setUpdatedAt(LocalDateTime.now());
            
            specialServiceImageMapper.insert(image);
        }
    }
    
    /**
     * 删除服务图片
     */
    private void deleteServiceImages(Integer serviceId) {
        specialServiceImageMapper.delete(
                new LambdaQueryWrapper<SpecialServiceImage>()
                        .eq(SpecialServiceImage::getServiceId, serviceId)
        );
    }
    
    /**
     * 获取同分类下的推荐服务
     */
    private List<SpecialService> getRecommendServicesByCategoryId(Integer categoryId, Integer excludeId, Integer limit) {
        return list(new LambdaQueryWrapper<SpecialService>()
                .eq(SpecialService::getCategoryId, categoryId)
                .eq(SpecialService::getStatus, 1)
                .ne(SpecialService::getId, excludeId)
                .orderByDesc(SpecialService::getSalesCount)
                .last("LIMIT " + limit));
    }
} 